package com.bocai.dahuatech.ui.activity;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.IndividualBean;
import com.bocai.dahuatech.Bean.LoginBean;
import com.bocai.dahuatech.Bean.PersonInfoBean;
import com.bocai.dahuatech.Bean.VersionBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseActivity;
import com.bocai.dahuatech.event.MainEvent;
import com.bocai.dahuatech.ui.frag.Fragment_Home;
import com.bocai.dahuatech.ui.frag.Fragment_Me;
import com.bocai.dahuatech.ui.frag.Fragment_Product;
import com.bocai.dahuatech.ui.frag.Fragment_ShoppingCart;
import com.bocai.dahuatech.utils.AESUtils;
import com.bocai.dahuatech.utils.DialogUtil;
import com.bocai.dahuatech.utils.DownLoadApkUtil;
import com.bocai.dahuatech.utils.RZUtil;
import com.bocai.dahuatech.utils.SharePrefencesUtil;
import com.google.gson.Gson;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 主页面
 */
public class HomeActivity extends BaseActivity implements View.OnClickListener
{
    @Bind(R.id.ll_home)
    LinearLayout llHome;
    @Bind(R.id.ll_product)
    LinearLayout llProduct;
    @Bind(R.id.ll_shoppingcart)
    LinearLayout llShoppingCard;
    @Bind(R.id.ll_me)
    LinearLayout llMe;
    private Fragment mFragProduct;
    private Fragment mFragHome;
    private Fragment mFragMe;
    private Fragment_ShoppingCart mFragShoppingCard;
    PersonInfoBean bean=new PersonInfoBean();
    LoginBean loginbean;
    int what;
    PackageInfo packageInfo;

    @Override
    protected int contentView()
    {
        return R.layout.activity_home;
    }

    @Override
    protected void initView()
    {
        ButterKnife.bind(this);
        packageInfo=getPackageInfo(this);
        getVersion();
        what=getIntent().getIntExtra("what",0);
        initEvent();
        if(SharePrefencesUtil.getFAccessFlag(this)!=0)
        {
            getLoginBean();
        }
        if(what==1){
            setSelect(2);
        }else{

            setSelect(0);
        }

    }

    private void getVersion() {
        getTestApi().getVersion(0)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast(R.string.neterror);
                    }

                    @Override
                    public void onNext(final BaseBean baseBean) {
                        if (baseBean.getReturnNo().equals("1")) {

                            String result = AESUtils.decode(baseBean.getContent());
                            Log.e("result",result);
                            final VersionBean versionBean=new Gson().fromJson(result,VersionBean.class);
                            if(!packageInfo.versionName.equals(versionBean.getName())){
                                if (versionBean.getIsForceUpgrade()==0){//非强制更新
                                    DialogUtil.dialogForTwoButton(HomeActivity.this, R.string.versioncontent, R.string.dismiss, R.string.update, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            DialogUtil.dismissTowDialog();
//                                            openBrower(versionBean.getLink());
//                                            downLoadApk(versionBean.getLink());
                                            new DownLoadApkUtil(HomeActivity.this,versionBean.getLink(),versionBean.getNo()).intoDownloadManager();
//                                            finish();
//                                            System.exit(0);

                                        }
                                    });
                                }else{//强制更新
                                    DialogUtil.dialogForTwoButtonfinish(HomeActivity.this, R.string.versioncontent, R.string.dismiss, R.string.update, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            DialogUtil.dismissTowDialog();
//                                            openBrower(versionBean.getLink());
                                            new DownLoadApkUtil(HomeActivity.this,versionBean.getLink(),versionBean.getNo()).intoDownloadManager();
                                            finish();
                                            System.exit(0);
                                        }
                                    }, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            finish();
                                            System.exit(0);
                                        }
                                    });
                                }
                            }

                        }
                    }
                });
    }
//    /*
// * 从服务器中下载APK
// */
//    protected void downLoadApk(final String url) {
//        final ProgressDialog pd;    //进度条对话框
//        pd = new  ProgressDialog(this);
//        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//        pd.setMessage("正在下载更新");
//        pd.show();
//        new Thread(){
//            @Override
//            public void run() {
//                try {
//                    File file =DownLoadManager. getFileFromServer(url, pd);
//                    sleep(3000);
//                    installApk(file);
//                    pd.dismiss(); //结束掉进度条对话框
//                } catch (Exception e) {
//                    Toast.makeText(HomeActivity.this,"下载新版本失败", Toast.LENGTH_SHORT).show();
////                    Message msg = new Message();
////                    msg.what = DOWN_ERROR;
////                    handler.sendMessage(msg);
//                    e.printStackTrace();
//                }
//            }}.start();
//    }
//    //安装apk
//    protected void installApk(File file) {
//        Intent intent = new Intent();
//        //执行动作
//        intent.setAction(Intent.ACTION_VIEW);
//        //执行的数据类型
//        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");//编者按：此处Android应为android，否则造成安装不了
//        startActivity(intent);
//    }
//
//    /*
// * 进入程序的主界面
// */
//    private void LoginMain(){
//        Intent intent = new Intent(this,HomeActivity.class);
//        startActivity(intent);
//        //结束掉当前的activity
//        this.finish();
//    }

    protected void openBrower(String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pi;
    }




    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN)
        {
            if((System.currentTimeMillis()-exitTime) > 2000)
            {
                Toast.makeText(getApplicationContext(), R.string.exitapp, Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else
            {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void getLoginBean()
    {
        getTestApi().login(SharePrefencesUtil.getuser_name(this),SharePrefencesUtil.getPsd(this),"Android")
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseBean>()
                {
                    @Override
                    public void onCompleted()
                    {

                    }

                    @Override
                    public void onError(Throwable e)
                    {

                    }

                    @Override
                    public void onNext(BaseBean baseBean)
                    {
                        if ("1".equals(baseBean.getReturnNo()))
                        {
                            String  ifpromotion=baseBean.getReturnInfo().toLowerCase();
                            SharedPreferences preferences=getSharedPreferences("user",MODE_PRIVATE);
                            SharedPreferences.Editor editor=preferences.edit();
                            editor.putString("ifpromotion",ifpromotion);
                            editor.commit();
                            String result = AESUtils.decode(baseBean.getContent());
                            result = start + result + end;
                            Log.e("result", result);
                            Gson gson = new Gson();
                            loginbean = gson.fromJson(result, LoginBean.class);
                            if(loginbean.getContent().get(0).getFToLower()==0)
                            {
                                DialogUtil.dialogForTwoButton(HomeActivity.this, R.string.changetoperson, R.string.know, R.string.toauthentication, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent1 = new Intent(HomeActivity.this, RegistDistributorSecendActivity.class);
                                        IndividualBean bean = new IndividualBean();
                                        intent1.putExtra("register", bean);
                                        intent1.putExtra("what", "certifiled");
                                        startActivity(intent1);
                                        DialogUtil.dismissTowDialog();
                                    }
                                });
                            }
                        }
                    }
                });
    }

    protected void initEvent()
    {
        llHome.setOnClickListener(this);
        llProduct.setOnClickListener(this);
        llShoppingCard.setOnClickListener(this);
        llMe.setOnClickListener(this);
    }


    @Override
    public void onEventMainThread(MainEvent event)
    {
        super.onEventMainThread(event);
        if(event.msg.equals("goshopcart"))
        {
            setSelect(2);
//            if(mFragShoppingCard!=null)
//            {
//                mFragShoppingCard.getShopcard();
//            }
        }
    }

    public void setSelect(int i)
    {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();

        switch (i)
        {
            case 0:
                resetImg();
                hideFragment(transaction);
                if (mFragHome == null)
                {
                    mFragHome = new Fragment_Home();
                    transaction.add(R.id.id_content, mFragHome);
                } else
                {
                    transaction.show(mFragHome);
                }

                llHome.setBackgroundColor(Color.parseColor("#e70014"));
                break;
            case 1:
                resetImg();
                hideFragment(transaction);
                if (mFragProduct == null)
                {
                    mFragProduct = new Fragment_Product();
                    transaction.add(R.id.id_content, mFragProduct);
                } else
                {
                    transaction.show(mFragProduct);
                }

                llProduct.setBackgroundColor(Color.parseColor("#e70014"));
                break;
            case 2:
                if(SharePrefencesUtil.getFAccessFlag(this)==0)//游客 去登录
                {
                    {
                        DialogUtil.dialogForTwoButton(this, R.string.nologin, R.string.know, R.string.tologin, new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
                                intent.putExtra("tologin", false);
                                startActivity(intent);
                                DialogUtil.dismissTowDialog();
                            }
                        });
                    }
                }
                else if(SharePrefencesUtil.getFAccessFlag(this)!=2) //个人  去认证
                {

                    DialogUtil.dialogForTwoButton(HomeActivity.this, R.string.notseeshoppingcard, R.string.know, R.string.toauthentication, new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if(SharePrefencesUtil.getFAccessFlag(HomeActivity.this)==6)
                            {
                                DialogUtil.dismissTowDialog();
                                DialogUtil.dialogForOneButton(HomeActivity.this, R.string.alreadysubmitdata,R.string.know);
                            }else  if(SharePrefencesUtil.getFAccessFlag(HomeActivity.this)==7)
                            {
                                RZUtil.renZheng(HomeActivity.this);
//                                Intent intent1=new Intent(HomeActivity.this,RegistDistributorSecendActivity.class);
//                                IndividualBean bean=new IndividualBean();
//                                intent1.putExtra("register",bean);
//                                intent1.putExtra("what", "certifiled");
//                                startActivity(intent1);
                                DialogUtil.dismissTowDialog();
                            }
                        }
                    });
                }else
                {
                    resetImg();
                    hideFragment(transaction);
                    if (mFragShoppingCard == null)
                    {
                        mFragShoppingCard = new Fragment_ShoppingCart();
                        transaction.add(R.id.id_content, mFragShoppingCard);
                    } else
                    {
                        transaction.show(mFragShoppingCard);
                    }
//                    mFragShoppingCard
                    llShoppingCard.setBackgroundColor(Color.parseColor("#e70014"));
                }
                break;
            case 3:
                if(SharePrefencesUtil.getFAccessFlag(this)==0)
                {
                    DialogUtil.dialogForTwoButton(this, R.string.nologin, R.string.know, R.string.tologin, new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            Intent intent=new Intent(HomeActivity.this, LoginActivity.class);
                            intent.putExtra("tologin", false);
                            startActivity(intent);
                            DialogUtil.dismissTowDialog();
                        }
                    });
                }else
                {
                    resetImg();
                    hideFragment(transaction);
                    if (mFragMe == null)
                    {
                        mFragMe = new Fragment_Me();
                        transaction.add(R.id.id_content, mFragMe);
                    } else
                    {
                        transaction.show(mFragMe);
                    }
                    llMe.setBackgroundColor(Color.parseColor("#e70014"));
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }


    private void resetImg()
    {
        llHome.setBackgroundColor(Color.parseColor("#373737"));
        llProduct.setBackgroundColor(Color.parseColor("#373737"));
        llShoppingCard.setBackgroundColor(Color.parseColor("#373737"));
        llMe.setBackgroundColor(Color.parseColor("#373737"));


    }

    private void hideFragment(FragmentTransaction transaction)
    {
        if (mFragHome != null)
        {
            transaction.hide(mFragHome);
        }
        if (mFragProduct != null)
        {
            transaction.hide(mFragProduct);
        }
        if (mFragShoppingCard != null)
        {
            transaction.hide(mFragShoppingCard);
        }
        if (mFragMe != null)
        {
            transaction.hide(mFragMe);
        }


    }

    @Override
    public void onClick(View v)
    {

        switch (v.getId())
        {
            case R.id.ll_home:
                setSelect(0);
                break;
            case R.id.ll_product:
                setSelect(1);
                break;
            case R.id.ll_shoppingcart:
                setSelect(2);
                break;
            case R.id.ll_me:
                setSelect(3);
                break;
        }
    }
}
